package com.yuntoyun.fwcore.util;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.content.res.XmlResourceParser;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.RawRes;

/**
 * 资源工具类
 */
public class FwResourceUtil {

    private static FwResourceUtil init = null;

    public static FwResourceUtil builder() {
        if (null == init) {
            init = new FwResourceUtil();
        }
        return init;
    }

    /**
     * Copy the file from assets.
     *
     * @param assetsFilePath The path of file in assets.
     * @param destFilePath   The path of destination file.
     * @return {@code true}: success<br>{@code false}: fail
     */
    public boolean copyFileFromAssets(final String assetsFilePath, final String
            destFilePath) {
        boolean res = true;
        try {
            String[] assets = FwApplicationUtil.appContext().getAssets().list(assetsFilePath);
            if (assets.length > 0) {
                for (String asset : assets) {
                    res &= copyFileFromAssets(assetsFilePath + "/" + asset, destFilePath + "/" +
                            asset);
                }
            } else {
                res = FwFileUtil.builder().writeFileFromIS(
                        new File(destFilePath),
                        FwApplicationUtil.appContext().getAssets().open(assetsFilePath),
                        false
                );
            }
        } catch (IOException e) {
            e.printStackTrace();
            res = false;
        }
        return res;
    }


    /**
     * Copy the file from raw.
     *
     * @param resId        The resource id.
     * @param destFilePath The path of destination file.
     * @return {@code true}: success<br>{@code false}: fail
     */
    public boolean copyFileFromRaw(@RawRes final int resId, final String destFilePath) {
        return FwFileUtil.builder().writeFileFromIS(new File(destFilePath),
                FwApplicationUtil.appContext().getResources().openRawResource(resId),
                false
        );
    }


    /**
     * 整体文件读取Asserts文件
     *
     * @param assetsFilePath
     * @param charsetName
     * @return
     */
    public String readAssertsSingleFile(final String assetsFilePath, final String charsetName) {
        InputStream is;
        try {
            is = FwApplicationUtil.appContext().getAssets().open(assetsFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return is2String(is, charsetName);
    }

    /**
     * 读取Asserts目录中多个子目录
     *
     * @param path
     * @return
     */
    public String[] readAssertsPath(final String path) {
        String[] list = null;
        try {
            list = FwApplicationUtil.appContext().getAssets().list(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 逐行读取Asserts文件
     *
     * @param assetsFilePath
     * @param charsetName
     * @return
     */
    public List<String> readAssertsSingleRow(final String assetsFilePath, final String
            charsetName) {
        InputStream is;
        try {
            is = FwApplicationUtil.appContext().getAssets().open(assetsFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return is2List(is, charsetName);
    }


    /**
     * 整体文件读取Raw文件
     *
     * @param resId
     * @param charsetName
     * @return
     */
    public String readRawSingleFile(final int resId, final String charsetName) {
        InputStream is = FwApplicationUtil.appContext().getResources().openRawResource(resId);
        return is2String(is, charsetName);
    }

    /**
     * 逐行读取Raw文件
     *
     * @param resId
     * @param charsetName
     * @return
     */
    public List<String> readRawSingleRow(final int resId, final String charsetName) {
        InputStream is = FwApplicationUtil.appContext().getResources().openRawResource(resId);
        return is2List(is, charsetName);
    }

    /**
     * 读取xml文件内容
     *
     * @param resId
     * @return
     */
    public String readXmlSingleFile(final int resId) {
        XmlResourceParser xml = FwApplicationUtil.appContext().getResources().getXml(resId);
        StringBuilder sb = new StringBuilder("");

        try {
            int typeXmlType = xml.getEventType();
            while (typeXmlType != XmlPullParser.END_DOCUMENT) {
                switch (typeXmlType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if ("Node".equals(xml.getName())) {
                            for (int i = 0; i < xml.getAttributeCount(); i++) {
                                sb.append(xml.getAttributeName(i) + "|||" + xml.getAttributeValue
                                        (i));
                                sb.append(FwSpanUtil.LINE_SEPARATOR);
                            }
                        }
                        break;
                    case XmlPullParser.TEXT:
                        sb.append(xml.getText());
                        sb.append(FwSpanUtil.LINE_SEPARATOR);
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                    case XmlPullParser.END_DOCUMENT:
                        break;
                }
                typeXmlType = xml.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    public List<String> is2List(final InputStream is,
                                final String charsetName) {
        BufferedReader reader = null;
        try {
            List<String> list = new ArrayList<>();
            if (FwFileUtil.builder().isSpace(charsetName)) {
                reader = new BufferedReader(new InputStreamReader(is));
            } else {
                reader = new BufferedReader(new InputStreamReader(is, charsetName));
            }
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String is2String(InputStream is, String charsetName) {

        byte[] bytes = FwFileUtil.builder().is2Bytes(is);
        if (bytes == null) return null;
        if (FwFileUtil.builder().isSpace(charsetName)) {
            return new String(bytes);
        } else {
            try {
                return new String(bytes, charsetName);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return "";
            }
        }
    }
}
